<?php

/******************************************************************
 * This file includes functions used by module and by callback.php
 ******************************************************************/

class HelperFunctions {
	
	
	/**
	 * Fill table sofort_orders with a new order
	 * @param int $ordersId
	 * @param string $paymentSecret
	 * @param object $invoice within a transaction-ID
	 * @return last insert_id
	 */
	function insertSofortOrder($ordersId, $paymentSecret, $invoice) {		
		if (!is_object($invoice) || !$invoice->transactionId) {
			return false;
		}
		
		//fill table sofort_orders
		$transactionId = $invoice->transactionId;
		$paymentMethod = 'rechnung_by_sofort';
		$sqlDataArray = array(
			'orders_id' => $ordersId,
			'transaction_id' => $transactionId,
			'payment_method' => $paymentMethod,
			'payment_secret' => $paymentSecret,
		);
		xtc_db_query(helperFunctions::getEscapedInsertInto('sofort_orders', $sqlDataArray));
		return xtc_db_insert_id(); // fetch and return the last insert id
	}
	
	
	/**
	 * Fill table sofort_orders_notification, e.g. in case of status-changes
	 * @param int $sofortOrdersId - key from table sofort_orders
	 * @param object $invoice within complete transactiondata
	 * @param string $customerComment (optional)
	 * @param string $sellerComment (optional)
	 * @return last insert_id
	 */
	function insertSofortOrdersNotification($sofortOrdersId, PnagInvoice $PnagInvoice, $customerComment = '', $sellerComment = '') {
		if (!is_object($PnagInvoice->transactionData) || $PnagInvoice->transactionData->getPaymentMethod() != 'sr') {
			return false;
		}
		
		if (!$sofortOrdersId) {
			return false;
		}
		
		$sqlDataArray = array(
			'sofort_orders_id' => $sofortOrdersId,
			'items' => serialize($PnagInvoice->getItems()),
			'amount' => $PnagInvoice->getAmount(),
			'customer_comment' => $customerComment,
			'seller_comment' => $sellerComment,
			'status_id' => $PnagInvoice->getState(),
			'status' => $PnagInvoice->getStatus(),
			'status_reason' => $PnagInvoice->getStatusReason(),
			'invoice_status' => $PnagInvoice->getStatusOfInvoice(),
			'invoice_objection' => $PnagInvoice->getInvoiceObjection());
		xtc_db_query(helperFunctions::getEscapedInsertInto('sofort_orders_notification', $sqlDataArray));
		return xtc_db_insert_id(); // fetch and return the last insert id
	}
	
	
	function getLastAmountFromSofortTable($ordersId){
		$query = xtc_db_query( 'SELECT id FROM sofort_orders WHERE orders_id = '.helperFunctions::escapeSql($ordersId));
		$result = xtc_db_fetch_array($query);
		$sofortOrdersId = $result['id'];
		$query = xtc_db_query( 'SELECT amount FROM sofort_orders_notification WHERE sofort_orders_id = "'.helperFunctions::escapeSql($sofortOrdersId).'" ORDER BY date_time DESC LIMIT 1');
		$result = xtc_db_fetch_array($query);
		$amount = $result['amount'];
		return $amount;
	}
	
	
	function getLastStatusIdFromSofortTable($ordersId){
		$query = xtc_db_query( 'SELECT id FROM sofort_orders WHERE orders_id = '.helperFunctions::escapeSql($ordersId));
		$result = xtc_db_fetch_array($query);
		$sofortOrdersId = $result['id'];
		$query = xtc_db_query( 'SELECT status_id FROM sofort_orders_notification WHERE sofort_orders_id = "'.helperFunctions::escapeSql($sofortOrdersId).'" ORDER BY date_time DESC LIMIT 1');
		$result = xtc_db_fetch_array($query);
		$statusId = $result['status_id'];
		return $statusId;
	}
	
	
	/**
	 * Converts a given String $string to any specified encoding (if supported)
	 *
	 * @param String $string
	 * @param String $to ; 2 = from utf-8 to shopencoding set in sofort.ini ; 3 = from shopencoding set in sofort.ini to utf-8
	 * @return String $string
	 */
	function convertEncoding($string, $to) {
		$shopEncoding = HelperFunctions::getIniValue('shopEncoding');
		
		if ($shopEncoding == 'UTF-8'){
			return $string;
		} elseif ($to == 2) {
			return mb_convert_encoding($string, $shopEncoding, 'UTF-8');
		} elseif ($to == 3){
			return mb_convert_encoding($string, 'UTF-8', $shopEncoding);
		}
	}
	
	
	/**
	 * escapes the given string via mysql_real_esacpe_string (if function exists & a db-connection is available) or mysql_escape_string
	 * @param string $string
	 * @return string $string
	 */
	function escapeSql($string) {
		if (function_exists('mysql_real_escape_string') && mysql_ping()) {
			return mysql_real_escape_string($string);
		} else {
			return mysql_escape_string($string);
		}
	}
	
	
	/**
	 * creates an escaped "INSERT INTO" sql-string
	 * @param string $table
	 * @param array $data with key=column_name and value=column_value
	 * for sql-commands set value like "sqlcommand:now()"
	 * @return string $returnString
	 */
	function getEscapedInsertInto($table, $data) {
		$table = trim($table);
		
		if (!is_string($table) || !$table) {
			return '';
		}
		
		if (!is_array($data) || !$data) {
			return '';
		}
		
		$returnString = 'INSERT INTO `'.helperFunctions::escapeSql($table).'` (`';
		$columns = array_keys($data);
		$returnString .= implode('`, `', $columns);
		$returnString .= '`) VALUES (';
		
		foreach ($data as $value) {
			if ((strpos($value, 'sqlcommand:') === 0)) {
				$returnString .= helperFunctions::escapeSql(substr($value, 11)).", ";  //its a sql-command
			}else{
				$returnString .= "'".helperFunctions::escapeSql($value)."', ";  //its a normal string or int
			}
		}
		
		$returnString = substr($returnString, 0, -2); //deletes comma and whitespace
		$returnString .= ')'; //dont add ';'
		return $returnString;
	}
	
	
	/**
	 * masks the given variable via strip_tags() and htmlentities()
	 * @param mixed $var
	 * @return mixed $var
	 */
	function htmlMask($var){
		return htmlentities(strip_tags($var),ENT_QUOTES,HelperFunctions::getIniValue('shopEncoding'));
	}
	
	
	/**
	 * masks the given arrayitem via strip_tags() and htmlentities()
	 * @param mixed $item
	 * @return mixed $item
	 */
	function htmlMaskArray(&$item){
		return htmlentities(strip_tags($item),ENT_QUOTES,HelperFunctions::getIniValue('shopEncoding'));
	}
	
	
	/**
	 * return from the sofort.ini the value of the given key
	 * @return mixed $value - if key is not found: false
	 */
	function getIniValue($key){
		$iniArray = parse_ini_file('sofort.ini');
		if (!isset($iniArray[$key])) {
			return false;
		}else{
			return $iniArray[$key];
		}
	}
}
?>